package com.incar.chuxing.baiduMap.MarkerOverlay;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.MainActivity;
import com.incar.chuxing.activity.PhotoViewActivity;
import com.incar.chuxing.activity.WebViewActivity;
import com.incar.chuxing.activity.driving.CarPositionActivity;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.baiduMap.BaiduMapParams;
import com.incar.chuxing.bean.CarListBean.AttachmentBean.ContentBean;
import com.incar.chuxing.bean.CityBoundBean;
import com.incar.chuxing.bean.OpenedCityListBean;
import com.incar.chuxing.bean.RechargeDotBean;
import com.incar.chuxing.repository.OrderRepository;
import com.incar.chuxing.utils.Dialogs.ChooseNaviDialog;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.RxBus;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.StateType;
import com.incar.chuxing.utils.ThreadPool;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.widget.MarqueeTextview;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * Created by Michael on 11/6.
 */

public class MarkerOverlay {
    private Context mContext;
    private BaiduMap mBaiduMap;
    public Map<String, Object> picMap = new HashMap<>();//存储图片信息，其中gradePic(Map), mapPic(Map<Map>),carTrack(Map)
    public Map<String, OverlayOptions> carMarkerOptionsMap = new HashMap(); //所有车Marker的配置list

    public Map<String, Overlay> nearTwentyMarkerList = new LinkedHashMap<>();


    private List<Overlay> rechargeDotMarkerList = new ArrayList<>();
    private List<Overlay> gasolineDotMarkerList = new ArrayList<>();
    /**
     * bitmapDescriptorMap键名
     * 普通的车：图片id + ",MapIcon"
     * 选中的车：图片id + ",SelectMapIcon"
     * 普通网点：网点车数+",MapIconPark"
     * 选中网点：网点车数+",SelectMapIconPark"
     * 城市图标：图片id + ",CityIcon"
     * 轨迹图标：图片id + ",TrackIcon"
     * 围栏图标：图片id + ",BoundIcon"
     */
    private HashMap<String, BitmapDescriptor> bitmapDescriptorMap = new HashMap<>();//所有地图Marker的图标BitmapDescriptor
    private Overlay selectedMarker;
    private Overlay sendCarMarker;
    public boolean hasCityMarker = false;//标记是否显示了城市marker

    public MarkerOverlay(Context mContext, BaiduMap mBaiduMap) {
        this.mContext = mContext;
        this.mBaiduMap = mBaiduMap;
    }

    public BitmapDescriptor createLocationIcon() {
        View carMarkerView = View.inflate(mContext, R.layout.location_icon, null);
        return BitmapDescriptorFactory.fromView(carMarkerView);
    }

    public void initSendCarEntry() {
        RxBus.getInstance().toObservable(StateType.State.class).subscribe(new Consumer<StateType.State>() {
            @Override
            public void accept(StateType.State state) throws Exception {
                if (state.equals(StateType.State.DEFAULT)) {
                    addSendCarMarker();
                } else if (sendCarMarker != null) {
                    sendCarMarker.remove();
                    sendCarMarker = null;
                }
            }
        });
    }


    public void addSendCarMarker() {
        if (StateType.isEqualsCurStates(StateType.State.DEFAULT) && SPUtils.getInstance(mContext).getIntValue(SPKey.IS_CITY_OPEN) == 1) {
            if (sendCarMarker != null) {
                sendCarMarker.remove();
                sendCarMarker = null;
            }
            LatLng myPosition = new LatLng(Double.parseDouble(MyApplication.getInstance().getCurPosition()[0]), Double.parseDouble(MyApplication.getInstance().getCurPosition()[1]));
            View carMarkerView = View.inflate(mContext, R.layout.layout_send_car, null);
            Bundle bundle = new Bundle();
            bundle.putString("markerType", MarkerType.SEND_CAR.name()); //标识marker类型
            MarkerOptions option = new MarkerOptions();
            option.position(myPosition)
                    //如果bitmapDescriptorMap中没保存有该图片，则使用本地默认的图片
                    .icon(BitmapDescriptorFactory.fromView(carMarkerView))
                    .zIndex(MarkerType.SEND_CAR.getZIndex())
                    .extraInfo(bundle);
            sendCarMarker = mBaiduMap.addOverlay(option);
        }
    }


    //标识marker类型,ZIndex表示Marker的层级，值越大层级越高
    public enum MarkerType {
        CAR(4),//车辆
        NEAR_CAR(4),//附近20辆中的非网点车
        SELECTED_CAR(6),
        RECHARGE_DOT(4),//行驶中充电网点
        GASOLINE_DOT(4),//加油站

        CITY(9),

        TRACK_ICON(7),

        BOUNDS_ICON(3),//禁停区中心marker

        SEND_CAR(12),//送车上门
        SEND_CAR_ORDER_LOC(3);//送车中marker
        private int ZIndex;

        MarkerType(int ZIndex) {
            this.ZIndex = ZIndex;
        }

        public int getZIndex() {
            return ZIndex;
        }
    }


    public String getDefaultIcon(String picName) {
        if (null == picMap || picMap.get("mapPic") == null
                || ((Map<String, Map<String, String>>) picMap.get("mapPic")).get(picName) == null) {
            //找不到类型,返回不存在图片id
            Logger.d("错误的picName " + picName);
            return "picNotExistId-getDefaultIcon";//如果图片id找不到，以此为id,Glide会加载失败，使用默认图片。
        }
        return ((Map<String, Map<String, String>>) picMap.get("mapPic")).get(picName).get("Default");
    }

    public String getSelectedIcon(String picName) {
        if (picName == null || null == picMap || picMap.get("mapPic") == null
                || ((Map<String, Map<String, String>>) picMap.get("mapPic")).get(picName) == null) {
            //找不到类型,返回不存在图片id
            Logger.d("错误的picName " + picName);
            return "picNotExistId-getSelectedIcon";
        }
        return ((Map<String, Map<String, String>>) picMap.get("mapPic")).get(picName).get("Selected");
    }

    public String getTrackIcon() {
        if (null == picMap || picMap.get("carTrack") == null
                || ((Map<String, String>) picMap.get("carTrack")).get("trackIcon") == null) {
            return "picNotExistId-getTrackIcon";
        }
        return ((Map<String, String>) picMap.get("carTrack")).get("trackIcon");
    }


    /********************************************************************************************************************************
     * 添加汽车
     */

    public void addCarsMarker(LinkedHashMap<String, ContentBean> perPageCarMap) {

        //添加车辆
        if (!perPageCarMap.isEmpty()) {
            //筛选出所有不同的图片，并放到Map中
            HashMap<String, Integer> picIdMap = new HashMap<>();

            for (ContentBean carBean : perPageCarMap.values()) {//foreach不能删除entries,可以使用iterator删除entries
                if (carBean.getGoldCarStatus() == 1) {//半金豆
                    if (!bitmapDescriptorMap.containsKey(carBean.getGoldPic() + ",MapIcon") && !picIdMap.containsKey(carBean.getGoldPic() + ",MapIcon")) {
                        picIdMap.put(carBean.getGoldPic() + ",MapIcon", R.drawable.icon_halfgoldbean); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                    }
                    if (!bitmapDescriptorMap.containsKey(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon") && !picIdMap.containsKey(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon")) {
                        picIdMap.put(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon", R.drawable.car_marker_selected);
                    }
                } else if (carBean.getGoldCarStatus() == 2) {//金豆
                    if (!bitmapDescriptorMap.containsKey(carBean.getGoldPic() + ",MapIcon") && !picIdMap.containsKey(carBean.getGoldPic() + ",MapIcon")) {
                        picIdMap.put(carBean.getGoldPic() + ",MapIcon", R.drawable.icon_goldbean); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                    }
                    if (!bitmapDescriptorMap.containsKey(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon") && !picIdMap.containsKey(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon")) {
                        picIdMap.put(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon", R.drawable.car_marker_selected);
                    }
                } else {//普通车
                    if (!bitmapDescriptorMap.containsKey(getDefaultIcon(carBean.getMapPic()) + ",MapIcon") && !picIdMap.containsKey(getDefaultIcon(carBean.getMapPic()) + ",MapIcon")) {
                        picIdMap.put(getDefaultIcon(carBean.getMapPic()) + ",MapIcon", R.drawable.car_marker); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                    }
                    if (!bitmapDescriptorMap.containsKey(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon") && !picIdMap.containsKey(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon")) {
                        picIdMap.put(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon", R.drawable.car_marker_selected);
                    }
                }
            }
            Logger.d("goldBean", "需要下载的图片" + picIdMap.toString());

            if (picIdMap.size() == 0) {//bitmapDescriptorMap不为空，即之前载过这些图片，直接使用已有的BitmapDescriptor
                Logger.d("使用已下载好的车辆Marker图片");
                addCarsToMap(perPageCarMap);
            } else {//之前未下载过这些图片，开始下载图片
                Logger.d("从网络下载车辆Marker图片--开始");
                new DownLoadImage().downLoadPic(picIdMap, loadedBitmaps -> {
                    //普通车图片和选中后的图片都下载完成，转成marker所需的BitmapDescriptor类型
                    View carMarkerView = View.inflate(mContext, R.layout.car_marker, null);
                    View sCarMarkerView = View.inflate(mContext, R.layout.car_marker_selected, null);
                    ImageView imageView = (ImageView) carMarkerView.findViewById(R.id.imageView);
                    ImageView sImageView = (ImageView) sCarMarkerView.findViewById(R.id.imageView);
                    for (Map.Entry<String, Bitmap> entry : loadedBitmaps.entrySet()) {
                        if (entry.getKey().split(",")[1].equals("MapIcon")) {//普通车的图片
                            imageView.setImageBitmap(entry.getValue());
                            bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(carMarkerView));
                        } else {//选中车的图片
                            sImageView.setImageBitmap(entry.getValue());
                            bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(sCarMarkerView));
                        }
                    }
                    //所有的图片都下载后，循环添加Marker到地图
                    Logger.d("从网络下载车辆Marker图片--转Descriptor完成");
                    addCarsToMap(perPageCarMap);
                });
            }
        }
    }


    private void addCarsToMap(LinkedHashMap<String, ContentBean> perPageCarMap) {
        ThreadPool.execute(() -> {
            HashMap<String, OverlayOptions> optionsList = new HashMap<>(); //Marker的配置list
            for (ContentBean carBean : perPageCarMap.values()) {
                MarkerOptions option = getOneMarkerOptions(carBean);
                optionsList.put(carBean.getId(), option);

            }
            carMarkerOptionsMap.putAll(optionsList);
            Logger.i("markersize", optionsList.size() + "size");
            if (StateType.isEqualsCurStates(StateType.State.DEFAULT)) { //如果是初始状态才渲染到地图上，否则只是保存数据
                mBaiduMap.addOverlays(new ArrayList<>(optionsList.values()));
            }
        });
    }

    @NonNull
    private MarkerOptions getOneMarkerOptions(ContentBean carBean) {
        if (carBean == null) {
            return null;
        }

        //设置marker
        Bundle bundle = new Bundle();
        bundle.putString("markerType", MarkerType.CAR.name()); //标识marker类型
        bundle.putString("carId", carBean.getId()); //标识marker的序号，用于点击后获取相应的数据
        MarkerOptions option = new MarkerOptions();
        //设置marker
        if (carBean.getGoldCarStatus() == 0) {//普通车
            option.position(new LatLng(carBean.getLatitude(), carBean.getLongitude()))
                    //如果bitmapDescriptorMap中没保存有该图片，则使用本地默认的图片
                    .icon(bitmapDescriptorMap.containsKey(
                            getDefaultIcon(carBean.getMapPic()) + ",MapIcon")
                            ? bitmapDescriptorMap.get(getDefaultIcon(carBean.getMapPic()) + ",MapIcon")
                            : BitmapDescriptorFactory.fromResource(R.drawable.car_marker))
                    .zIndex(MarkerType.CAR.getZIndex())
                    .extraInfo(bundle);
        } else {//金豆车
            option.position(new LatLng(carBean.getLatitude(), carBean.getLongitude()))
                    //如果bitmapDescriptorMap中没保存有该图片，则使用本地默认的图片
                    .icon(bitmapDescriptorMap.containsKey(
                            carBean.getGoldPic() + ",MapIcon")
                            ? bitmapDescriptorMap.get(carBean.getGoldPic() + ",MapIcon")
                            : BitmapDescriptorFactory.fromResource(R.drawable.car_marker))
                    .zIndex(MarkerType.CAR.getZIndex())
                    .extraInfo(bundle);
        }
        return option;
    }


    /**
     * 所有车maker已保存过，直接添加到地图
     */
    public void addAllCars() {
        Logger.d("markerList", carMarkerOptionsMap.size() + "");
        if (carMarkerOptionsMap != null && carMarkerOptionsMap.size() != 0) {
            ThreadPool.execute(() -> {
                //如果主页面是初始状态才渲染到地图上
                if (StateType.isEqualsCurStates(StateType.State.DEFAULT)) {
                    mBaiduMap.addOverlays(new ArrayList<>(carMarkerOptionsMap.values()));
                }
                StateType.loadState = StateType.LoadMarkerState.LOAD_DONE;
            });
        }
    }


    /**
     * 更新已保存的maker的信息
     */
    public void updateOneMarkerInfo(ContentBean carBean) {
        HashMap<String, Integer> picIdMap = new HashMap<>();
        if (carBean.getGoldCarStatus() == 1) {//半金豆
            if (!bitmapDescriptorMap.containsKey(carBean.getGoldPic() + ",MapIcon") && !picIdMap.containsKey(carBean.getGoldPic() + ",MapIcon")) {
                picIdMap.put(carBean.getGoldPic() + ",MapIcon", R.drawable.icon_halfgoldbean); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
            }
        } else if (carBean.getGoldCarStatus() == 2) {//金豆
            if (!bitmapDescriptorMap.containsKey(carBean.getGoldPic() + ",MapIcon") && !picIdMap.containsKey(carBean.getGoldPic() + ",MapIcon")) {
                picIdMap.put(carBean.getGoldPic() + ",MapIcon", R.drawable.icon_goldbean); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
            }
        } else {//普通车
            if (!bitmapDescriptorMap.containsKey(getDefaultIcon(carBean.getMapPic()) + ",MapIcon") && !picIdMap.containsKey(getDefaultIcon(carBean.getMapPic()) + ",MapIcon")) {
                picIdMap.put(getDefaultIcon(carBean.getMapPic()) + ",MapIcon", R.drawable.car_marker); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
            }
        }

        if (picIdMap.size() == 0) {//bitmapDescriptorMap不为空，即之前载过这些图片，直接使用已有的BitmapDescriptor
            Logger.d("使用已下载好的车辆Marker图片");
            MarkerOptions option = getOneMarkerOptions(carBean);
            carMarkerOptionsMap.remove(carBean.getId());
            carMarkerOptionsMap.put(carBean.getId(), option);
        } else {//之前未下载过这些图片，开始下载图片
            new DownLoadImage().downLoadPic(picIdMap, loadedBitmaps -> {
                //普通车图片和选中后的图片都下载完成，转成marker所需的BitmapDescriptor类型
                View carMarkerView = View.inflate(mContext, R.layout.car_marker, null);
                ImageView imageView = (ImageView) carMarkerView.findViewById(R.id.imageView);
                for (Map.Entry<String, Bitmap> entry : loadedBitmaps.entrySet()) {
                    if (entry.getKey().split(",")[1].equals("MapIcon")) {//普通车的图片
                        imageView.setImageBitmap(entry.getValue());
                        bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(carMarkerView));
                    }
                }
                //所有的图片都下载后
                MarkerOptions option = getOneMarkerOptions(carBean);
                carMarkerOptionsMap.remove(carBean.getId());
                carMarkerOptionsMap.put(carBean.getId(), option);
            });

        }
    }


    /*********************************************************************************************************************************
     * 添加附近20辆网点和汽车
     */

    public void addNearTwentyMarker(List<ContentBean> carList) {
        //附近车辆
        if (carList != null && !carList.isEmpty()) {
            //筛选出所有不同的图片，并放到Map中
            HashMap<String, Integer> picIdMap = new HashMap<>();
            for (ContentBean carBean : carList) {
                if (carBean.getGoldCarStatus() == 1) {//半金豆
                    if (!bitmapDescriptorMap.containsKey(carBean.getGoldPic() + ",MapIcon") && !picIdMap.containsKey(carBean.getGoldPic() + ",MapIcon")) {
                        picIdMap.put(carBean.getGoldPic() + ",MapIcon", R.drawable.icon_halfgoldbean); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                        picIdMap.put(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon", R.drawable.car_marker_selected);
                    }
                } else if (carBean.getGoldCarStatus() == 2) {//金豆
                    if (!bitmapDescriptorMap.containsKey(carBean.getGoldPic() + ",MapIcon") && !picIdMap.containsKey(carBean.getGoldPic() + ",MapIcon")) {
                        picIdMap.put(carBean.getGoldPic() + ",MapIcon", R.drawable.icon_goldbean); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                        picIdMap.put(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon", R.drawable.car_marker_selected);
                    }
                } else {//普通车
                    if (!bitmapDescriptorMap.containsKey(getDefaultIcon(carBean.getMapPic()) + ",MapIcon") && !picIdMap.containsKey(getDefaultIcon(carBean.getMapPic()) + ",MapIcon")) {
                        picIdMap.put(getDefaultIcon(carBean.getMapPic()) + ",MapIcon", R.drawable.car_marker); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                        picIdMap.put(getSelectedIcon(carBean.getMapPic()) + ",SelectMapIcon", R.drawable.car_marker_selected);
                    }
                }
            }
            if (picIdMap.size() == 0) {//bitmapDescriptorMap不为空，即之前载过这些图片，直接使用已有的BitmapDescriptor
                Logger.d("使用已下载好的附近车辆Marker图片");
                addNearCarsToMap(carList);
            } else {//之前未下载过这些图片，开始下载图片
                Logger.d("从网络下载附近车辆Marker图片--开始");
                new DownLoadImage().downLoadPic(picIdMap, loadedBitmaps -> {
                    //普通车图片和选中后的图片都下载完成，转成marker所需的BitmapDescriptor类型
                    View carMarkerView = View.inflate(mContext, R.layout.car_marker, null);
                    View sCarMarkerView = View.inflate(mContext, R.layout.car_marker_selected, null);
                    ImageView imageView = (ImageView) carMarkerView.findViewById(R.id.imageView);
                    ImageView sImageView = (ImageView) sCarMarkerView.findViewById(R.id.imageView);
                    for (Map.Entry<String, Bitmap> entry : loadedBitmaps.entrySet()) {
                        if (entry.getKey().split(",")[1].equals("MapIcon")) {//普通车的图片
                            imageView.setImageBitmap(entry.getValue());
                            bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(carMarkerView));
                        } else {//选中车的图片
                            sImageView.setImageBitmap(entry.getValue());
                            bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(sCarMarkerView));
                        }

                    }
                    //所有的图片都下载后，循环添加Marker到地图
                    Logger.d("从网络下载附近车辆Marker图片--转Descriptor完成");
                    addNearCarsToMap(carList);
                });
            }
        }
    }

    private void addNearCarsToMap(List<ContentBean> carList) {
        List<OverlayOptions> optionsList = new ArrayList<>(); //所有Marker的配置list
        Logger.d("附近车辆数" + carList.size() + "");
        for (ContentBean carModelsBean : carList) {
            //设置marker
            Bundle bundle = new Bundle();
            bundle.putString("markerType", MarkerType.NEAR_CAR.name()); //标识marker类型
            bundle.putString("carId", carModelsBean.getId());

            if (carModelsBean.getGoldCarStatus() == 0) {//普通车
                OverlayOptions option = new MarkerOptions()
                        .position(new LatLng(carModelsBean.getLatitude(), carModelsBean.getLongitude()))
                        .icon(bitmapDescriptorMap
                                .containsKey(getDefaultIcon(carModelsBean.getMapPic()) + ",MapIcon") ? bitmapDescriptorMap.get(getDefaultIcon(carModelsBean.getMapPic()) + ",MapIcon") : BitmapDescriptorFactory.fromResource(R.drawable.car_marker))
                        .zIndex(MarkerType.NEAR_CAR.getZIndex())
                        .extraInfo(bundle);
                optionsList.add(option);
            } else {//金豆车
                OverlayOptions option = new MarkerOptions()
                        .position(new LatLng(carModelsBean.getLatitude(), carModelsBean.getLongitude()))
                        .icon(bitmapDescriptorMap
                                .containsKey(carModelsBean.getGoldPic() + ",MapIcon") ? bitmapDescriptorMap.get(carModelsBean.getGoldPic() + ",MapIcon") : BitmapDescriptorFactory.fromResource(R.drawable.car_marker))
                        .zIndex(MarkerType.NEAR_CAR.getZIndex())
                        .extraInfo(bundle);
                optionsList.add(option);
            }


        }
        List<Overlay> list = mBaiduMap.addOverlays(optionsList);
        for (Overlay overlay : list) {
            nearTwentyMarkerList.put(overlay.getExtraInfo().getString("carId"), overlay);
        }
    }


    /*********************************************************************************************************************************
     * 添加行程中充电桩
     */

    private int loadCarPicCount = 0;

    public void addReChargeDotMarker(
            final List<RechargeDotBean.AttachmentBean.ElectricStationBean> electricStationBeans) {

        //添加车辆，由于车辆图标多，采用下载完所有车的图片后，再批量添加Marker的形式
        if (electricStationBeans != null && !electricStationBeans.isEmpty()) {
            //所有Marker的配置list
            final List<OverlayOptions> optionsList = new ArrayList<>();
            //所有类型的图片Id
            final List<String> picIdList = new ArrayList<>();
            //得到所有类型的图片Id
            for (int i = 0; i < electricStationBeans.size(); i++) {
                if (!picIdList.contains(electricStationBeans.get(i).getMapIcon())) {
                    picIdList.add(electricStationBeans.get(i).getMapIcon());
                }
            }
            loadCarPicCount = 0;
            //下载所有类型的图片
            for (int i = 0; i < picIdList.size(); i++) {
                final int finalI = i;
                Glide.with(mContext.getApplicationContext()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + picIdList.get(finalI)).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        loadCarPicCount++;
                        View view = View.inflate(mContext, R.layout.recharge_marker, null);
                        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
                        imageView.setImageBitmap(bitmap);
                        bitmapDescriptorMap.put(picIdList.get(finalI), BitmapDescriptorFactory.fromView(view));
                        //所有的图片都下载后，循环添加Marker
                        if (loadCarPicCount == picIdList.size()) {
                            ThreadPool.execute(() -> {
                                for (int j = 0; j < electricStationBeans.size(); j++) {
                                    //设置marker
                                    final Bundle bundle = new Bundle();
                                    bundle.putString("markerType", MarkerType.RECHARGE_DOT.name()); //标识marker类型
                                    bundle.putInt("carMarkerId", j); //标识marker的序号，用于点击后获取相应的数据
                                    //设置marker
                                    OverlayOptions option = new MarkerOptions()
                                            .position(new LatLng(electricStationBeans.get(j).getLatitude(), electricStationBeans.get(j).getLongitude()))
                                            .icon(bitmapDescriptorMap.containsKey(electricStationBeans.get(j).getMapIcon()) ? bitmapDescriptorMap.get(electricStationBeans.get(j).getMapIcon()) : BitmapDescriptorFactory.fromResource(R.drawable.icon_recharge))
                                            .zIndex(MarkerType.RECHARGE_DOT.getZIndex())
                                            .extraInfo(bundle);
                                    optionsList.add(option);
                                }
                                rechargeDotMarkerList = mBaiduMap.addOverlays(optionsList);
                            });
                        }
                    }
                });
            }

        }
    }

    /*********************************************************************************************************************************
     *添加行程中加油站
     */

    public void addGasolineDotMarker(List<PoiInfo> poiInfos) {
        ThreadPool.execute(() -> {
            try {
                final List<OverlayOptions> optionsList = new ArrayList<>();
                for (int j = 0; j < poiInfos.size(); j++) {
                    //设置marker
                    final Bundle bundle = new Bundle(1);
                    bundle.putString("markerType", MarkerType.GASOLINE_DOT.name()); //标识marker类型
                    //设置marker
                    OverlayOptions option = new MarkerOptions()
                            .position(poiInfos.get(j).location)
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_gasstation))
                            .zIndex(MarkerType.GASOLINE_DOT.getZIndex())
                            .extraInfo(bundle);
                    optionsList.add(option);
                }
                gasolineDotMarkerList.addAll(mBaiduMap.addOverlays(optionsList));
            } catch (Exception e) {

            }

        });
    }

    /*********************************************************************************************************************************
     * 添加一个寻车时车的marker
     */

    public void addFindCar(final LatLng position, String selectedMapIcon) {
        Logger.i("seleccarpic", selectedMapIcon);
        selectedMapIcon = getSelectedIcon(selectedMapIcon);
        //删除原来的大图标
        clearSelectedMarker();
        Logger.i("seleccarpic2", selectedMapIcon);
        View view = View.inflate(mContext, R.layout.car_marker_selected, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
        Glide.with(mContext.getApplicationContext()).load(((MyApplication) MyApplication.getInstance()).getImageUrl() + selectedMapIcon).asBitmap().error(R.drawable.car_marker_selected).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                imageView.setImageBitmap(bitmap);
                mBaiduMap.addOverlay(new MarkerOptions()
                        .position(position)
                        .icon(BitmapDescriptorFactory.fromView(view)).zIndex(MarkerType.SELECTED_CAR.getZIndex()));
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                mBaiduMap.addOverlay(new MarkerOptions()
                        .position(position)
                        .icon(BitmapDescriptorFactory.fromView(view)).zIndex(MarkerType.SELECTED_CAR.getZIndex()));
            }
        });
    }


    /*********************************************************************************************************************************
     * 添加一个选中的汽车marker
     *
     * 恢复上一个小图
     * 删除上一个大图
     * 隐藏下一个小图
     * 添加下一个大图
     */
    private String lastSelectedCarId;

    public void addSelectedCar(ContentBean
                                       carBean, LinkedHashMap<String, ContentBean> allCarList, boolean recordLastSelected) {
        //删除当前选中的图标
        Logger.i("carsGold", "选中的图标" + carBean.getId() + "");
        if (nearTwentyMarkerList.get(carBean.getId()) != null) {
            nearTwentyMarkerList.get(carBean.getId()).remove();
            nearTwentyMarkerList.remove(carBean.getId());
        }

        //添加并更新上一个选中的图标
        if (allCarList.get(lastSelectedCarId) != null) {
            nearTwentyMarkerList.put(lastSelectedCarId, mBaiduMap.addOverlay(getOneMarkerOptions(allCarList.get(lastSelectedCarId))));
            Logger.i("carsGold", "恢复图标" + lastSelectedCarId);
        }
        if (recordLastSelected) {
            lastSelectedCarId = carBean.getId();//记录当前选中的carId
        }
        //删除原来的大图标
        clearSelectedMarker();


        //添加新的大图标
        String selectMapIcon = getSelectedIcon(carBean.getMapPic());
        Logger.d("loadmarkerKey", selectMapIcon + ",SelectMapIcon");
        LatLng position = new LatLng(carBean.getLatitude(), carBean.getLongitude());
        if (bitmapDescriptorMap.get(selectMapIcon + ",SelectMapIcon") == null) {
            View sCarMarkerView = View.inflate(mContext, R.layout.car_marker_selected, null);
            selectedMarker = mBaiduMap
                    .addOverlay(new MarkerOptions()
                            .position(position)
                            .zIndex(MarkerType.SELECTED_CAR.getZIndex())
                            .icon(BitmapDescriptorFactory.fromView(sCarMarkerView)));
        } else {
            selectedMarker = mBaiduMap
                    .addOverlay(new MarkerOptions()
                            .position(position)
                            .zIndex(MarkerType.SELECTED_CAR.getZIndex())
                            .icon(bitmapDescriptorMap.get(selectMapIcon + ",SelectMapIcon")));
        }

    }


    /*********************************************************************************************************************************
     * 添加行车轨迹起始点
     */

    public void addLineStartIcon(final double latitude, final double longitude) {
        HashMap<String, Integer> picIdMap = new HashMap<>();
        if (!bitmapDescriptorMap.containsKey(getTrackIcon() + ",TrackIcon") && !picIdMap.containsKey(getTrackIcon() + ",TrackIcon")) {
            picIdMap.put(getTrackIcon() + ",TrackIcon", R.drawable.icon_return_track); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
        }

        if (picIdMap.size() != 0) {
            new DownLoadImage().downLoadPic(picIdMap, loadedBitmaps -> {
                View view = View.inflate(mContext, R.layout.line_start_marker, null);
                ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
                for (Map.Entry<String, Bitmap> entry : loadedBitmaps.entrySet()) {
                    imageView.setImageBitmap(entry.getValue());
                    bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(view));
                }
                mBaiduMap.addOverlay(new MarkerOptions()
                        .position(new LatLng(latitude, longitude))
                        .anchor(0.5f, 0.5f)
                        .zIndex(MarkerType.TRACK_ICON.getZIndex())
                        .icon(bitmapDescriptorMap.containsKey(
                                getTrackIcon() + ",TrackIcon")
                                ? bitmapDescriptorMap.get(getTrackIcon() + ",TrackIcon")
                                : BitmapDescriptorFactory.fromResource(R.drawable.icon_return_track)));
            });
        } else {
            mBaiduMap.addOverlay(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    .anchor(0.5f, 0.5f)
                    .zIndex(MarkerType.TRACK_ICON.getZIndex())
                    .icon(bitmapDescriptorMap.containsKey(
                            getTrackIcon() + ",TrackIcon")
                            ? bitmapDescriptorMap.get(getTrackIcon() + ",TrackIcon")
                            : BitmapDescriptorFactory.fromResource(R.drawable.icon_return_track)));
        }
    }

    /**********************************************************************************************************************************
     送车上门预订单marker*/
    public void addPreOrderMarker(LatLng latLng) {
        Bundle bundle = new Bundle();
        bundle.putString("markerType", MarkerType.SEND_CAR_ORDER_LOC.name()); //标识Marker类型
        RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.deliver_send_car_marker, null);
        if (latLng != null) {
            mBaiduMap.addOverlay(new MarkerOptions()
                    .position(latLng)
                    .anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromView(relativeLayout))
                    .zIndex(3)
                    .extraInfo(bundle));
        }
    }

    public interface DeliverPhoneClickListener {
        void onClick();

    }

    public void showDeliverCarOrderLocInfoWindow(LatLng carPosition) {
        //初始化marker的InfoWindow
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.layout_deliver_send_car, null);
        InfoWindow mInfoWindow = new InfoWindow(infoWindow, carPosition,
                -(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, mContext.getResources().getDisplayMetrics()));
        mBaiduMap.showInfoWindow(mInfoWindow);
    }

    public void showDeliverCarOrderLocInfoWindowAndPhone(LatLng carPosition,
                                                         final DeliverPhoneClickListener clickListener) {
        //初始化marker的InfoWindow
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.layout_deliver_send_car_phone, null);
        infoWindow.setOnClickListener(v -> clickListener.onClick());
        InfoWindow mInfoWindow = new InfoWindow(infoWindow, carPosition,
                -(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, mContext.getResources().getDisplayMetrics()));
        mBaiduMap.showInfoWindow(mInfoWindow);
    }

    /**********************************************************************************************************************************
     *添加城市图标
     */
    public void createCitiesMarker
    (List<OpenedCityListBean.AttachmentBean.CityListBean> cityListBeans) {
        //添加城市图标
        if (cityListBeans != null && !cityListBeans.isEmpty()) {
            //筛选出所有不同的图片，并放到Map中
            HashMap<String, Integer> picIdMap = new HashMap<>();
            for (OpenedCityListBean.AttachmentBean.CityListBean cityBean : cityListBeans) {
                if (!bitmapDescriptorMap.containsKey(cityBean.getCityIcon() + ",CityIcon") && !picIdMap.containsKey(cityBean.getCityIcon() + ",CityIcon")) {
                    picIdMap.put(cityBean.getCityIcon() + ",CityIcon", R.drawable.city_default); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                }
            }
            if (picIdMap.size() != 0) {//bitmapDescriptorMap不为空，即之前载过这些图片，直接使用已有的BitmapDescriptor
                //之前未下载过这些图片，开始下载图片
                Logger.d("从网络下载城市Marker图片--开始");
                new DownLoadImage().downLoadPic(picIdMap, loadedBitmaps -> {
                    View cityMarkerView = View.inflate(mContext, R.layout.city_marker, null);
                    ImageView imageView = (ImageView) cityMarkerView.findViewById(R.id.imageView);
                    for (Map.Entry<String, Bitmap> entry : loadedBitmaps.entrySet()) {
                        imageView.setImageBitmap(entry.getValue());
                        bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(cityMarkerView));
                        Logger.d("loadmarkerKey1", entry.getKey());
                    }
                    Logger.d("从网络下载城市Marker图片--转Descriptor完成");
                });
            }
        }
    }


    public void addCitiesToMap
            (List<OpenedCityListBean.AttachmentBean.CityListBean> cityListBeans) {
        if (cityListBeans != null && cityListBeans.size() != 0) {
            hasCityMarker = true;
            List<OverlayOptions> optionsList = new ArrayList<>();
            for (OpenedCityListBean.AttachmentBean.CityListBean cityListBean : cityListBeans) {
//设置marker
                final Bundle bundle = new Bundle();
                bundle.putString("markerType", MarkerType.CITY.name()); //标识marker类型
                bundle.putString("cityCode", cityListBean.getAreaCode());
                //设置marker
                OverlayOptions option = new MarkerOptions()
                        .position(new LatLng(cityListBean.getLatitude(), cityListBean.getLongitude()))
                        .icon(bitmapDescriptorMap.containsKey(cityListBean.getCityIcon() + ",CityIcon") ? bitmapDescriptorMap.get(cityListBean.getCityIcon() + ",CityIcon") : BitmapDescriptorFactory.fromResource(R.drawable.city_default))
                        .zIndex(MarkerType.CITY.getZIndex())
                        .extraInfo(bundle);
                Logger.d("添加了" + cityListBean.getCityName());
                optionsList.add(option);
            }
            mBaiduMap.addOverlays(optionsList);
        }
    }

    /********************************************************************************************************************************
     * 禁停区Marker
     */
    public void addBoundMarker(List<CityBoundBean.AttachmentBean.FenceAreaBean> allBounds) {
        //添加城市图标
        if (allBounds != null && !allBounds.isEmpty()) {
            //筛选出所有不同的图片，并放到Map中
            HashMap<String, Integer> picIdMap = new HashMap<>();
            for (CityBoundBean.AttachmentBean.FenceAreaBean bound : allBounds) {
                if (!TextUtils.isEmpty(bound.getCenterIcon()) && !bound.getCenterIcon().equals("0")
                        && !bitmapDescriptorMap.containsKey(bound.getCenterIcon() + ",BoundIcon")
                        && !picIdMap.containsKey(bound.getCenterIcon() + ",BoundIcon")) {
                    picIdMap.put(bound.getCenterIcon() + ",BoundIcon", R.drawable.no_parking); //key:id+类型(普通图片，选中图片) value:下载失败的默认图片
                }
            }
            if (picIdMap.size() == 0) {//bitmapDescriptorMap不为空，即之前载过这些图片，直接使用已有的BitmapDescriptor
                Logger.d("使用已下载好的禁停区Marker图片");
                addBoundMarkerToMap(allBounds);
            } else {//bitmapDescriptorMap不为空，即之前载过这些图片，直接使用已有的BitmapDescriptor
                //之前未下载过这些图片，开始下载图片
                Logger.d("从网络下载禁停区Marker图片--开始");
                new DownLoadImage().downLoadPic(picIdMap, loadedBitmaps -> {
                    View cityMarkerView = View.inflate(mContext, R.layout.no_parking, null);
                    ImageView imageView = (ImageView) cityMarkerView.findViewById(R.id.imageView);
                    for (Map.Entry<String, Bitmap> entry : loadedBitmaps.entrySet()) {
                        imageView.setImageBitmap(entry.getValue());
                        bitmapDescriptorMap.put(entry.getKey(), BitmapDescriptorFactory.fromView(cityMarkerView));
                    }
                    //所有的图片都下载后，循环添加Marker到地图
                    Logger.d("从网络下载禁停区Marker图片--转Descriptor完成");
                    addBoundMarkerToMap(allBounds);
                });
            }
        }
    }


    public void addBoundMarkerToMap
            (List<CityBoundBean.AttachmentBean.FenceAreaBean> allBounds) {
        if (allBounds != null && allBounds.size() != 0) {
            List<OverlayOptions> optionsList = new ArrayList<>();
            for (CityBoundBean.AttachmentBean.FenceAreaBean bound : allBounds) {

                if (!TextUtils.isEmpty(bound.getCenterIcon()) && !bound.getCenterIcon().equals("0")) {
//设置marker
                    final Bundle bundle = new Bundle();
                    bundle.putString("markerType", MarkerType.BOUNDS_ICON.name()); //标识marker类型
                    //设置marker
                    OverlayOptions option = new MarkerOptions()
                            .position(new LatLng(bound.getCenterLat(), bound.getCenterLng()))
                            .icon(bitmapDescriptorMap.containsKey(bound.getCenterIcon() + ",BoundIcon") ? bitmapDescriptorMap.get(bound.getCenterIcon() + ",BoundIcon") : BitmapDescriptorFactory.fromResource(R.drawable.city_default))
                            .zIndex(MarkerType.BOUNDS_ICON.getZIndex())
                            .extraInfo(bundle);
                    Logger.d("添加了一个禁停区" + bound.getCenterLng() + "  " + bound.getCenterLat());
                    optionsList.add(option);
                }
            }
            if (!optionsList.isEmpty())
                mBaiduMap.addOverlays(optionsList);
        }
    }


    public void showCarLocationInfoWindow(ContentBean contentBean) {
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.layout_car_location_bean_windows, null);
        RelativeLayout pics = (RelativeLayout) infoWindow.findViewById(R.id.rl_user_commit);
        TextView windows_location = (TextView) infoWindow.findViewById(R.id.windows_location);
        MarqueeTextview location_offset = (MarqueeTextview) infoWindow.findViewById(R.id.windows_location_offset);
        LinearLayout layout_bean = (LinearLayout) infoWindow.findViewById(R.id.windows_location_bean);
        TextView bean_desc = (TextView) infoWindow.findViewById(R.id.windows_location_bean_desc);
        TextView bean_type = (TextView) infoWindow.findViewById(R.id.windows_location_bean_type);

        //用户拍摄图片
        if (!TextUtils.isEmpty(contentBean.getImgs()) && !contentBean.getImgs().equals("0") && !contentBean.getImgs().equals("null") && contentBean.getImgs().split(",").length > 0) {
            ImageView imageView = (ImageView) infoWindow.findViewById(R.id.iv_user_commit);
            imageView.setOnClickListener((View view) -> {
                Intent intent = new Intent(mContext, PhotoViewActivity.class);
                intent.putStringArrayListExtra("pictures", new ArrayList<String>(Arrays.asList(contentBean.getImgs().split(","))));
                int location[] = new int[2];
                imageView.getLocationOnScreen(location);
                intent.putExtra("left", location[0]);
                intent.putExtra("top", location[1]);
                intent.putExtra("height", imageView.getHeight());
                intent.putExtra("width", imageView.getWidth());
                mContext.startActivity(intent);
                ((MainActivity) mContext).isExecuteOnResumeCheckOrder = false;//返回主页面时不在执行onResume检查未完成订单
                ((MainActivity) mContext).overridePendingTransition(0, 0);
            });
        } else {
            pics.setVisibility(View.GONE);
        }

        //位置偏差
        if (contentBean.getIsAccurate() == 2) {
            location_offset.setVisibility(View.VISIBLE);
        } else {
            location_offset.setVisibility(View.GONE);
        }

        //位置描述
        if (!TextUtils.isEmpty(contentBean.getRemarkMsg())) {
            //初始化marker的InfoWindow
            windows_location.setText(contentBean.getRemarkMsg());//车辆位置
        }

        //金豆车
        if (contentBean.getGoldCarStatus() != 0) {
            layout_bean.setVisibility(View.VISIBLE);
            bean_desc.setText(contentBean.getShow_text());
            bean_type.setText(contentBean.getLink_text());

            bean_type.setOnClickListener(view -> {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, contentBean.getLink_href());
                mContext.startActivity(intent);
            });
        }

        InfoWindow mInfoWindow = new InfoWindow(infoWindow, new LatLng(contentBean.getLatitude(), contentBean.getLongitude()),
                -(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 55, mContext.getResources().getDisplayMetrics()));
        mBaiduMap.showInfoWindow(mInfoWindow);
    }


    /**********************************************************************************************************************************
     * 寻车中车位置信息框
     */
    public void showFindCarInfoWindow(ContentBean contentBean, int type) {
        //初始化marker的InfoWindow
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.layout_find_car_bean, null);
        TextView windows_location = (TextView) infoWindow.findViewById(R.id.location);
        RelativeLayout pics = (RelativeLayout) infoWindow.findViewById(R.id.rl_user_commit);
        TextView navi = (TextView) infoWindow.findViewById(R.id.navi);
        LinearLayout layout_bean = (LinearLayout) infoWindow.findViewById(R.id.windows_location_bean);
        TextView bean_desc = (TextView) infoWindow.findViewById(R.id.windows_location_bean_desc);
        TextView bean_type = (TextView) infoWindow.findViewById(R.id.windows_location_bean_type);
        TextView sen_done = infoWindow.findViewById(R.id.send_done);

        if (OrderRepository.bookType == 4) {
            sen_done.setVisibility(View.VISIBLE);
        }
        //用户拍摄图片
        if (!TextUtils.isEmpty(contentBean.getImgs()) && !contentBean.getImgs().equals("0") && !contentBean.getImgs().equals("null") && contentBean.getImgs().split(",").length > 0) {
            ImageView imageView = (ImageView) infoWindow.findViewById(R.id.iv_user_commit);
            imageView.setOnClickListener((View view) -> {
                Intent intent = new Intent(mContext, PhotoViewActivity.class);
                intent.putStringArrayListExtra("pictures", new ArrayList<String>(Arrays.asList(contentBean.getImgs().split(","))));
                int location[] = new int[2];
                imageView.getLocationOnScreen(location);
                intent.putExtra("left", location[0]);
                intent.putExtra("top", location[1]);
                intent.putExtra("height", imageView.getHeight());
                intent.putExtra("width", imageView.getWidth());
                mContext.startActivity(intent);
                if (type == 0) {
                    ((MainActivity) mContext).isExecuteOnResumeCheckOrder = false;//返回主页面时不在执行onResume检查未完成订单
                    ((MainActivity) mContext).overridePendingTransition(0, 0);
                } else if (type == 1) {
                    ((CarPositionActivity) mContext).overridePendingTransition(0, 0);
                }
            });
        } else {
            pics.setVisibility(View.GONE);
        }


        //位置描述
        if (!TextUtils.isEmpty(contentBean.getRemarkMsg())) {
            //初始化marker的InfoWindow
            windows_location.setText(contentBean.getRemarkMsg());//车辆位置
        }

        //金豆车
        if (contentBean.getGoldCarStatus() != 0) {
            layout_bean.setVisibility(View.VISIBLE);
            bean_desc.setText(contentBean.getShow_text());
            bean_type.setText(contentBean.getLink_text());

            bean_type.setOnClickListener(view -> {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, contentBean.getLink_href());
                mContext.startActivity(intent);
            });
        } else {
            layout_bean.setVisibility(View.GONE);
        }
        navi.setOnClickListener(v -> showNaviDialog(new LatLng(contentBean.getLatitude(), contentBean.getLongitude())));
        InfoWindow mInfoWindow = new InfoWindow(infoWindow, new LatLng(contentBean.getLatitude(), contentBean.getLongitude()),
                -(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 55, mContext.getResources().getDisplayMetrics()));
        mBaiduMap.showInfoWindow(mInfoWindow);
    }


    /**********************************************************************************************************************************
     * 行程中车信息框
     */

    private TextView textView_inUse_time;
    private TextView textView_inUse_km;
    private TextView textView_return_time;
    private LinearLayout layout_return_time;

    public void showDrivingCarInfoWindow(String longtime, double distance, String endTime, LatLng markerPosition) {
        //初始化marker的InfoWindow
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.drivingcar_marker_infowindow, null);
        textView_inUse_time = infoWindow.findViewById(R.id.textView_inUse_time);
        textView_inUse_km = infoWindow.findViewById(R.id.textView_inUse_km);
        textView_return_time = infoWindow.findViewById(R.id.textView_return_time);
        layout_return_time = infoWindow.findViewById(R.id.layout_return_time);
        textView_inUse_time.setText(longtime);
        textView_inUse_km.setText(new DecimalFormat("0.00km").format(distance));
        if (!TextUtils.isEmpty(endTime)) {
            layout_return_time.setVisibility(View.VISIBLE);
            textView_return_time.setText(endTime);
        } else {
            layout_return_time.setVisibility(View.GONE);
        }


        InfoWindow mInfoWindow = new InfoWindow(infoWindow, markerPosition,
                -(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, mContext.getResources().getDisplayMetrics()));
        mBaiduMap.showInfoWindow(mInfoWindow);

    }


    /**********************************************************************************************************************************
     * 行程中充电桩
     */

    public interface NaviButtonClickListener {
        void onClick();

    }

    public void showFindRechargeDotInfoWindow(String content, LatLng carPosition,
                                              final NaviButtonClickListener clickListener) {
        //初始化marker的InfoWindow
        View infoWindow = LayoutInflater.from(mContext).inflate(R.layout.layout_find_recharge_window, null);
        TextView location = (TextView) infoWindow.findViewById(R.id.location);
        TextView navi = (TextView) infoWindow.findViewById(R.id.navi);
        location.setText(content);
        navi.setOnClickListener(v -> clickListener.onClick());
        InfoWindow mInfoWindow = new InfoWindow(infoWindow, carPosition,
                -(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, mContext.getResources().getDisplayMetrics()));
        mBaiduMap.showInfoWindow(mInfoWindow);
    }


    public void hideInfoWindow() {
        mBaiduMap.hideInfoWindow();
    }


    /**********************************************************************************************************************************
     * 清除行驶中充电桩Marker
     */

    public void removeRechargeDotMarker() {
        try {
            if (rechargeDotMarkerList != null && rechargeDotMarkerList.size() != 0) {
                for (int i = 0; i < rechargeDotMarkerList.size(); i++) {
                    rechargeDotMarkerList.get(i).remove();
                }
                rechargeDotMarkerList.clear();
            }
        } catch (Exception e) {

        }
    }

    /**********************************************************************************************************************************
     * 清除行程中加油站Marker
     */

    public void removeGasolineDotMarker() {
        try {
            if (gasolineDotMarkerList != null && gasolineDotMarkerList.size() != 0) {
                for (int i = 0; i < gasolineDotMarkerList.size(); i++) {
                    gasolineDotMarkerList.get(i).remove();
                }
                gasolineDotMarkerList.clear();
            }
        } catch (Exception e) {

        }
    }


    /**********************************************************************************************************************************
     * 清除地图上20辆车的Marker
     */

    public void removeNearTwentyMarker() {
        for (Overlay overlay : nearTwentyMarkerList.values()) {
            overlay.remove();
        }
        nearTwentyMarkerList.clear();
        lastSelectedCarId = "";
    }

    /**********************************************************************************************************************************
     * 清除选中的车Marker
     */
    public void clearSelectedMarker() {
        if (selectedMarker != null) {
            selectedMarker.remove();
            selectedMarker = null;
        }
    }


    /**********************************************************************************************************************************
     * 清除地图上网点和车辆的Marker
     */

    public void clearData() {
        Logger.d("清除所有");
        lastSelectedCarId = "";
        nearTwentyMarkerList.clear();
        rechargeDotMarkerList.clear();
        gasolineDotMarkerList.clear();
        selectedMarker = null;
        hasCityMarker = false;
    }

    /**********************************************************************************************************************************
     *导航选择Dialog
     */
    private void showNaviDialog(LatLng carPosition) {
        final ChooseNaviDialog chooseNaviDialog = new ChooseNaviDialog(mContext);
        chooseNaviDialog.setOnItemClickListener(position -> {
            LatLng curPosition = new LatLng(Double.parseDouble(((MyApplication) mContext.getApplicationContext()).getCurPosition()[0]),
                    Double.parseDouble(((MyApplication) mContext.getApplicationContext()).getCurPosition()[1]));

            if (position == 0) {
                // 构建 route搜索参数以及策略，起终点也可以用name构造
                RouteParaOption para = new RouteParaOption()
                        .startPoint(curPosition)
                        .endPoint(carPosition);
                try {
                    BaiduMapRoutePlan.openBaiduMapWalkingRoute(para, mContext);
                } catch (Exception e) {
                    ToastUtils.makeText(mContext, "未安装百度地图", ToastUtils.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            } else {
                LatLng gaoDeCurPosition = BaiduMapParams.gaoDeToBaidu(curPosition);
                LatLng gaoDeCarPosition = BaiduMapParams.gaoDeToBaidu(carPosition);
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setPackage("com.autonavi.minimap");
                intent.setData(Uri.parse("amapuri://route/plan/?sourceApplication=大道用车&slat=" + gaoDeCurPosition.latitude + "&slon=" + gaoDeCurPosition.longitude + "&dlat=" + gaoDeCarPosition.latitude + "&dlon=" + gaoDeCarPosition.longitude + "&dev=0&t=2"));
                if (SDCardUtils.checkApkExist(mContext, "com.autonavi.minimap")) {
                    try {
                        mContext.startActivity(intent);
                        Logger.d("GasStation", "高德地图客户端已经安装");
                    } catch (Exception e) {
                        ToastUtils.makeText(mContext, "启动高德地图失败", ToastUtils.LENGTH_SHORT).show();
                    }

                } else {
                    ToastUtils.makeText(mContext, "未安装高德地图", ToastUtils.LENGTH_SHORT).show();
                }
            }
            chooseNaviDialog.dismiss();
        });
        chooseNaviDialog.show();
    }
}
